const express = require('express');
const cors = require('cors');
const mysql = require('mysql2/promise');

const app = express();
app.use(cors());
app.use(express.json());

const PORT = Number(process.env.MATERIALS_PORT || 8082);
const HOST = process.env.MATERIALS_HOST || '0.0.0.0';

// MySQL Connection Pool
const dbPool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '8209230329',
  database: 'soa_lab1',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 初始化数据库表
const initializeDatabase = async () => {
  try {
    const connection = await dbPool.getConnection();
    await connection.query(`
      CREATE TABLE IF NOT EXISTS materials (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        category VARCHAR(255) DEFAULT '未分类',
        location VARCHAR(255) DEFAULT '未指定',
        status VARCHAR(50) DEFAULT 'available',
        description TEXT,
        borrowerName VARCHAR(255) DEFAULT ''
      );
    `);
    console.log('Database table "materials" is ready.');
    connection.release();
  } catch (error) {
    console.error('Failed to initialize database:', error);
    process.exit(1); // Exit if DB initialization fails
  }
};

// CRUD endpoints
app.get('/materials', async (req, res, next) => {
  try {
    const [rows] = await dbPool.query('SELECT * FROM materials');
    res.json(rows);
  } catch (error) {
    next(error);
  }
});

app.get('/materials/:id', async (req, res, next) => {
  try {
    const id = Number(req.params.id);
    const [rows] = await dbPool.query('SELECT * FROM materials WHERE id = ?', [id]);
    if (rows.length === 0) return res.status(404).json({ error: 'not_found' });
    res.json(rows[0]);
  } catch (error) {
    next(error);
  }
});

app.post('/materials', async (req, res, next) => {
  try {
    const payload = req.body || {};
    if (!payload.name) {
      return res.status(400).json({ error: '物资名称不能为空' });
    }

    const item = {
      name: payload.name,
      category: payload.category || '未分类',
      location: payload.location || '未指定',
      status: payload.status || 'available',
      description: payload.description || '',
      borrowerName: payload.borrowerName || ''
    };

    const [result] = await dbPool.query('INSERT INTO materials SET ?', item);
    const [newItem] = await dbPool.query('SELECT * FROM materials WHERE id = ?', [result.insertId]);
    res.status(201).json(newItem[0]);
  } catch (error) {
    next(error);
  }
});

app.put('/materials/:id', async (req, res, next) => {
  try {
    const id = Number(req.params.id);
    const payload = req.body || {};

    const [rows] = await dbPool.query('SELECT * FROM materials WHERE id = ?', [id]);
    if (rows.length === 0) return res.status(404).json({ error: 'not_found' });

    // 只更新传入的字段
    const updateFields = {};
    Object.keys(payload).forEach(key => {
      if (['name', 'category', 'location', 'status', 'description', 'borrowerName'].includes(key)) {
        updateFields[key] = payload[key];
      }
    });

    if (Object.keys(updateFields).length === 0) {
      return res.json(rows[0]); // No fields to update
    }

    await dbPool.query('UPDATE materials SET ? WHERE id = ?', [updateFields, id]);
    const [updatedRows] = await dbPool.query('SELECT * FROM materials WHERE id = ?', [id]);
    res.json(updatedRows[0]);
  } catch (error) {
    next(error);
  }
});

app.delete('/materials/:id', async (req, res, next) => {
  try {
    const id = Number(req.params.id);
    const [result] = await dbPool.query('DELETE FROM materials WHERE id = ?', [id]);
    if (result.affectedRows === 0) return res.status(404).json({ error: 'not_found' });
    res.status(204).send();
  } catch (error) {
    next(error);
  }
});

// 健康检查端点
app.get('/', (req, res) => {
  res.json({
    message: 'Materials service is running',
    database: 'MySQL',
    endpoints: {
      'GET /materials': '获取所有物资',
      'GET /materials/:id': '获取单个物资',
      'POST /materials': '创建物资',
      'PUT /materials/:id': '更新物资',
      'DELETE /materials/:id': '删除物资'
    }
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: '服务器内部错误' });
});

// 404 处理
app.use((req, res) => {
  res.status(404).json({ error: '接口不存在' });
});

const startServer = async () => {
  await initializeDatabase();
  app.listen(PORT, HOST, () => {
    console.log(`Materials service listening on ${HOST}:${PORT}`);
    console.log(`Health check: http://${HOST === '0.0.0.0' ? 'localhost' : HOST}:${PORT}`);
  });
};

startServer();